#!/bin/bash
echo "start cmd :> $0 $1 $2 $3 $4 $5 $6 $7"

DATA_ROOT=$1
BAK_ROOT=$2
Relative_Path=$3
DATA_PATH=${DATA_ROOT}"/"${Relative_Path}
TABLE=$4
DATABASE_ADDRESS=$5
DATABASE_USER=$6
DATABASE_PASS=$7

#test dirctory exist?
if [ ! -x "${BAK_ROOT}" ] ; then 
	mkdir -p "${BAK_ROOT}" 
fi

FILES=(`find ${DATA_PATH}`)

FILECOUNT=${#FILES[@]}
index=1
while [ $index -lt ${FILECOUNT} ]
do
	fullFilePath=${FILES[$index]}
	relativeFilePath=${fullFilePath##${DATA_ROOT}}
	backupFullPath=${BAK_ROOT}${relativeFilePath}
  	echo ":> ${fullFilePath}  -> ${relativeFilePath} -> ${backupFullPath}"
  	#execute sql stat
  	#tee ${DATA_PATH}/tmp.log
	mysql -u${DATABASE_USER} -p${DATABASE_PASS} -h${DATABASE_ADDRESS} -e"
	load data local infile '${fullFilePath}' into table ${TABLE} FIELDS TERMINATED BY ',' ENCLOSED BY '\'';
	quit"

	#remove log file after import
	#`rm -rf ${fullFilePath}`
	#back up logger file
	#test dirctory exist?
	dirctory="${backupFullPath%/*}"
	echo "dirctory : ${dirctory}"
	if [ ! -x "${dirctory}" ] ; then 
		echo "make dirctory : ${dirctory}"
		mkdir -p "${dirctory}" 
	fi
	echo "move file :${fullFilePath} to ${backupFullPath}"
	`mv ${fullFilePath} ${backupFullPath}`
	let "index= $index + 1" 
done

#skip data path
let "FILECOUNT= $FILECOUNT - 1"

echo "Count :> ${FILECOUNT}"
